export class FetchSSEAdapter {
  constructor(options) {
    this.options = options;
    this.controller = null;
    this.supportsSend = false;
    
    // 重试配置
    this.retryCount = 0;
    this.maxRetries = options.maxRetries ?? 3; // 最大重试次数
    this.retryDelay = options.retryDelay ?? 2000; // 基础重试间隔
    this.retryBackoffFactor = options.retryBackoffFactor ?? 1.5; // 退避系数

    // 心跳配置
    this.heartbeatInterval = options.heartbeatInterval ?? 25000; // 心跳检测间隔
    this.heartbeatTimeout = options.heartbeatTimeout ?? 30000; // 无数据超时时间
    this.lastActivityTime = 0; // 最后活动时间戳
    this.heartbeatTimer = null; // 心跳检测定时器

    // 状态控制
    this.isExplicitDisconnect = false; // 是否主动断开
  }

  connect({ onMessage, onOpen, onClose, onError }) {
    if (this.isExplicitDisconnect) return;
    
    this.controller = new AbortController();
    this.lastActivityTime = Date.now();

    // 清理旧定时器
    this._clearHeartbeatTimer();

    // 配置请求参数
    const init = {
      method: this.options.method || 'GET',
      headers: this.options.headers || {},
      signal: this.controller.signal,
      ...(this.options.body && { body: this.options.body })
    };

    fetch(this.options.url, init)
      .then(response => {
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        if (!response.body) throw new Error('Streaming not supported');

        onOpen?.();
        this.retryCount = 0; // 重置重试计数器

        // 启动心跳检测
        this._startHeartbeatCheck();

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        let eventType = 'message'; // 默认事件类型
        let data = '';
        let id = '';

        const processStream = ({ done, value }) => {
          if (done) {
            this._handleDisconnect(onClose);
            return;
          }

          // 更新最后活动时间
          this.lastActivityTime = Date.now();
          
          buffer += decoder.decode(value, { stream: true });

          // 解析 SSE 事件流格式
          while (buffer.includes('\n\n')) {
            const eventEndIndex = buffer.indexOf('\n\n');
            const chunk = buffer.slice(0, eventEndIndex);
            buffer = buffer.slice(eventEndIndex + 2);

            chunk.split('\n').forEach(line => {
              const colonIndex = line.indexOf(':');
              if (colonIndex <= 0) return;

              const field = line.slice(0, colonIndex).trim();
              const value = line.slice(colonIndex + 1).trim();

              switch (field) {
                case 'event':
                  eventType = value;
                  break;
                case 'data':
                  data += value + '\n';
                  break;
                case 'id':
                  id = value;
                  break;
                case 'retry':
                  this.retryDelay = parseInt(value, 10);
                  break;
              }
            });

            // 触发事件回调
            if (data) {
              const result = {
                type: eventType,
                data: this.options.format === 'json' ? JSON.parse(data.trim()) : data.trim(),
                id,
                retry: this.retryDelay
              };

              onMessage?.(result);
              
              // 重置临时变量
              data = '';
              eventType = 'message';
            }
          }
          
          // 继续读取流
          return reader.read().then(processStream);
        };

        return reader.read().then(processStream);
      })
      .catch(err => {
        if (err.name === 'AbortError') return;
        this._handleRetry(err, onError, onClose);
      });
  }

  disconnect() {
    this.isExplicitDisconnect = true;
    this.controller?.abort();
    this._clearHeartbeatTimer();
  }

  /* ------------------------ 私有方法 ------------------------ */
  _startHeartbeatCheck() {
    this.heartbeatTimer = setInterval(() => {
      const idleTime = Date.now() - this.lastActivityTime;
      if (idleTime > this.heartbeatTimeout) {
        console.warn(`心跳超时 (${idleTime}ms)，触发重连`);
        this.controller?.abort();
        this._handleRetry(new Error('Heartbeat timeout'), null, null);
      }
    }, this.heartbeatInterval);
  }

  _clearHeartbeatTimer() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }

  _handleDisconnect(onClose) {
    this._clearHeartbeatTimer();
    onClose?.();
    if (!this.isExplicitDisconnect) {
      this._handleRetry(new Error('Connection closed'), null, null);
    }
  }

  _handleRetry(err, onError, onClose) {
    this._clearHeartbeatTimer();
    
    if (this.retryCount >= this.maxRetries) {
      onError?.(new Error(`超过最大重试次数 (${this.maxRetries})`));
      onClose?.();
      return;
    }

    const delay = this.retryDelay * (this.retryBackoffFactor ** this.retryCount);
    this.retryCount++;
    
    console.log(`将在 ${Math.round(delay/1000)} 秒后重试 (${this.retryCount}/${this.maxRetries})`);
    
    setTimeout(() => {
      this.connect({ onMessage, onOpen, onClose, onError });
    }, delay);
    
    onError?.(err);
  }
}